package com.zhiyou100.reflect;

import java.lang.reflect.Field;

public class Demo6 {

    public static void main(String[] args) throws IllegalAccessException {
        User user = new User();
        user.setEmail("78645642@163.com");
        Class<User> userClass = User.class;
        //获取所有声明的字段
        Field[] fields = userClass.getDeclaredFields();
        for (Field field : fields) {
            System.out.println("field.getName() = " + field.getName());
            //获取类型
            Class<?> type = field.getType();
            System.out.println("type = " + type);
            //获取指定对象属性的值  要求属性不能是私有的
            Object o = field.get(user);
            System.out.println("o = " + o);
            if (field.getName().equals("username")) {
                field.set(user,"xueyin");
            }
            if (field.getName().equals("age")){
                if (field.getType().equals(int.class)){
                    field.setInt(user,20);
                }
            }
        }
        System.out.println("user = " + user);
    }
}
